package com.sinsz.common.exception;

import com.sinsz.common.Result;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.springframework.util.StringUtils;

/**
 * 统一异常处理
 * @author chenjianbo
 */
public class ApiException extends RuntimeException {

    private IError error;

    public ApiException() {
        this(DefaultError.SYSTEM_ERR_01);
    }

    public ApiException(IError error) {
        super(Json.toJson(new Result(error.errCode(),error.errMsg()), JsonFormat.tidy()));
        this.error = error;
    }

    public ApiException(final int errCode, final String errMsg) {
        this(new IError() {
            @Override
            public int errCode() {
                return errCode;
            }

            @Override
            public String errMsg() {
                return StringUtils.isEmpty(errMsg) ? "未知异常" : errMsg;
            }
        });
    }

    IError getError() {
        return error;
    }

    @Override
    public String toString() {
        Result result = new Result(this.error.errCode(), this.error.errMsg());
        result.setCause(super.getCause());
        return result.toString();
    }

}